<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" @ok="handleSubmit" width="650px" destroyOnClose>
    <BasicForm @register="registerForm" >
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, ref, unref} from 'vue';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {BasicForm, useForm} from '/@/components/Form/index';

import {formSchema} from './task.data';
import {getTask, saveOrUpdateTask} from './task.api';
import {useMessage} from '/@/hooks/web/useMessage';

const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);

const activeKey = ref('base')
// const templateVarRel = ref()
const tplVarDefines = ref<any[]>()

//表单配置
const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  schemas: formSchema,
  labelWidth: 90,
  showActionButtonGroup: false,
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
});
//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //重置表单
  await resetFields();
  activeKey.value = 'base'
  tplVarDefines.value = []
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    setDrawerProps({ loading: true })
    try {
      // 获取详情
      const record = await getTask({ id: data.record.id })
      tplVarDefines.value = record.tplVarDefines
      //表单赋值
      await setFieldsValue({
        ...record
      });
    } finally {
      setDrawerProps({ loading: false })
    }
  }
});

//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增推送任务' : '编辑推送任务'));

// 监听表格被渲染之后, 设置数据源
// watch(
//   () => templateVarRel.value,
//   (val) => {
//     templateVarRel.value && templateVarRel.value.setDataSource(tplVarDefines.value)
//   }
// );

// watch(
//   () => tplVarDefines.value,
//   (val) => {
//     if (templateVarRel.value) {
//       templateVarRel.value && templateVarRel.value.setDataSource(tplVarDefines.value)
//     } 
//   }
// );


const handleTabChange = (key) => {
  activeKey.value = key;
}


//表单提交事件
async function handleSubmit(v) {
  try {
    let values = await validate();
    values = {...values }
    console.log("form: ", values)
    setDrawerProps({ confirmLoading: true });

    //提交表单
    await saveOrUpdateTask({
      ...values, 
    }, isUpdate.value);
    //关闭弹窗
    closeDrawer();
    //刷新列表
    emit('success');
    createMessage.success(`${title.value}成功`)
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>

<style lang="less"> 

.select-channel {
  color: #40a9ff;
  margin-left: 1px;
  cursor: pointer;
  font-size: 14px;
}
</style>
